<?php
/*********************************************
 *  CPG Dragonfly™ CMS
 *********************************************
	Copyright © since 2010 by CPG-Nuke Dev Team
	http://dragonflycms.org

	Dragonfly is released under the terms and conditions
	of the GNU GPL version 2 or any later version
*/

class Dragonfly_Modules
{
	protected static
		$active = array(),
		$list = array();

	# ls('intall/cpg_inst.php,index.php');
	# ls('index.php')
	public static function ls($child='', $active=true)
	{
		if (false !== strpos($child, './')) return array();
		$search = implode(',modules/*/', array_map('trim', explode(',', $child)));
		$active = $active ? 'active_' : '';

		if (!isset(self::$list[$active.$child]))
		{
			$files = glob('{modules/*/'.$search.'}', GLOB_BRACE); // BASEDIR issues C:\\dir\\file
			$modules = preg_replace('#^modules\/([a-zA-Z0-9_]+)\/.*#', '$1', $files);
			self::$list[$active.$child] = array_combine($modules, $files);
			if ($active)
			{
				self::$list[$active.$child] = array_intersect_key(self::$list[$active.$child], self::getActiveList());
			}
		}
		return self::$list[$active.$child];
	}

	public static function clearStatCache()
	{
		self::$list = array();
	}

	public static function getActiveList()
	{
		if (empty(self::$active)) {
			$K = Dragonfly::getKernel();
			if ($c = $K->CACHE->get('active_modules'))
			{
				self::$active = $c;
			}
			else
			{
				$result = $K->SQL->query("SELECT title, version FROM {$K->SQL->TBL->modules} WHERE active=1");
				while ($row = $result->fetch_row()) {
					self::$active[$row[0]] = (intval($row[1]) > 0) ? $row[1] : 1;
				}
				# Cache everything
				$K->CACHE->set('active_modules', self::$active);
			}
		}
		return self::$active;
	}

	public static function isActive($module_name)
	{
		self::getActiveList();
		return isset(self::$active[$module_name]) ? self::$active[$module_name] : 0;
	}

}
